/*
 *@author lwh created
 *
 *
 *
 */

#include "thread_pool.h"
#define CONVERSION_NUM 1024 // 内存单位进制转化

void getsCommand(task_t * task)
{
    // 读取文件名
    // printf("execute gets command.\n");
    // char filename[32] = {0}; //文件名 
    // strcpy(filename, task->data);
    // printf("filename: %s\n", filename); //打印文件名
    printf("getsCommand.\n");

    int ret = -1;
    int exist_flag = 0;
    ret = recvn(task->peerfd, &exist_flag, sizeof(exist_flag));
    if(ret == -1){
        printf("recvn_exist_flag_err\n");
    }

    if(exist_flag == 1){
        break_point(task);

    }else{

        //打开文件
        int fd = open(task->data, O_RDONLY);
        if(fd < 0){ perror("open"); return; }

        //获取文件长度
        off_t len = lseek(fd, 0, SEEK_END);
        if(len < 0){  perror("lseek"); close(fd); return;}
        lseek(fd, 0, SEEK_SET); //重置偏移到开头 
        ret = sendn(task->peerfd, &len, sizeof(len)); //发送文件长度 
        if(ret < 0) {
            perror("sendn");
            close(fd);
            return;
        }
        printf("file len: %ld\n", len);
        // @zg 判断文件是否大于 100MB，如果大于则使用sendfile进行零拷贝传输
        long size_in_mb = len / (CONVERSION_NUM * CONVERSION_NUM);
        if (size_in_mb > 100) {
            while ((ret = sendfile(task->peerfd, fd, 0L, len)) > 0);
            if (ret == -1) {
                perror("sendfile");
            }
            close(fd);
            return;
        }

        // 发送文件到client
        char buff[1000] = {0};
        off_t left = len;
        while(left > 0) {
            memset(buff, 0, sizeof(buff));
            ssize_t read_count = read(fd, buff, sizeof(buff)); // 读取文件
            if(read_count < 0) {
                perror("read");
                break;
            }  else if(read_count == 0) {
                break;
            }

            //继续传文件
            ret = sendn(task->peerfd, buff, read_count);
            if(ret < 0) {
                perror("sendn");
                break;
            }

            left -= ret;
        }
        close(fd);
    }
}
